import streamlit as st
from PIL import Image
import io
from jing import WDWXReport, jing_names
import pandas as pd

# Streamlit app
report = None
qr_image = None #"./qrcode.png"
st.title("微动微修")
col0, col1 = st.columns(2)
with col0:
    input_txt = st.text_area("输入数据", height=350)
    make_qrcode = st.button("生成二维码")
    if make_qrcode:
        report = WDWXReport.from_string(input_txt)
        qr_image = report.make_qrcode().get_image()
with col1:
    if qr_image is None:
        st.text("二维码示例")
        qr_image = "./qrcode.png"
    st.image(qr_image)
uploaded_file = st.file_uploader("上传二维码", type=["jpg", "jpeg", "png"])

if uploaded_file is not None:
    if uploaded_file.type.startswith('image'):
        image = Image.open(io.BytesIO(uploaded_file.read()))
        report = WDWXReport.from_qrcode(image)
    
if report is None or len(report.contents) == 0:
    st.sidebar.write("请输入诊断报告数据或上传一张二维码")
else:
    st.sidebar.write("报告目录")
    df = pd.DataFrame(columns=['ID', '经络', '分值'])
    for i, key in enumerate(jing_names):
        jing = report.contents[key]
        df.loc[len(df)] = [i+1, key, jing.score()]                
            
    st_df = st.sidebar.dataframe(df, use_container_width=True, height=len(jing_names) * 40,
                                    selection_mode="single-row",
                                    hide_index=True)
    
    for i, key in enumerate(jing_names):
        jing = report.contents[key]
        st.markdown(f"# {i + 1} {key} {jing.score()}")
        # col0, col1 = st.columns(2)
        # with col0:
        for j in range(8):
            end = min(j * 8 + 8, len(jing.data))
            st.markdown(' '.join([str(num) for num in jing.data[j * 8: end]]) + '\n')
        # with col1:
        st.pyplot(jing.plot()) 

